/**
 * fshows.com
 * Copyright (C) 2013-2021 All Rights Reserved.
 */
package com.fshows.leshuapay.sdk.client.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.fshows.leshuapay.sdk.client.UploadFileClient;
import com.fshows.leshuapay.sdk.exception.LeshuaException;
import com.fshows.leshuapay.sdk.request.UploadVideoRequest;
import com.fshows.leshuapay.sdk.response.LeshuaBaseResponse;
import com.fshows.leshuapay.sdk.response.UploadFileResponse;
import com.fshows.leshuapay.sdk.util.BrushMD5;
import com.fshows.leshuapay.sdk.util.DateUtil;
import com.fshows.leshuapay.sdk.util.FsHttpUtil;
import com.fshows.leshuapay.sdk.util.ReqSerialNoUtil;
import com.fshows.leshuapay.sdk.util.SignUtil;
import com.fshows.leshuapay.sdk.util.StringPool;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Map;

/**
 * @author ruanzeyang
 * @version UploadFileClientImpl.java, v 0.1 2021-12-23 13:41 ruanzeyang
 */
@Data
@Slf4j
public class UploadFileClientImpl implements UploadFileClient {

    /**
     * 图片文件上传的临时目录
     */
    public static final String FILE_SAVE_TEMP_DIR = SystemUtils.getUserHome() +
            File.separator + "files" +
            File.separator + "upload" +
            File.separator + "leshua" +
            File.separator + "temp" +
            File.separator;
    /**
     * 乐刷成功标识
     */
    private static final String SUCCESS = "000000";
    /**
     * 请求地址
     */
    private String serverUrl;
    /**
     * 服务商id
     */
    private String agentId;
    /**
     * 服务商私钥
     */
    private String privateKey;


    public UploadFileClientImpl(String serverUrl, String agentId, String privateKey) {
        this.serverUrl = serverUrl;
        this.agentId = agentId;
        this.privateKey = privateKey;
    }

    @Override
    public UploadFileResponse upload(String filePath, String subAgentId) throws Exception {
        return this.upload(serverUrl, null, StrUtil.blankToDefault(subAgentId, agentId), privateKey, filePath);
    }

    @Override
    public UploadFileResponse upload(String filePath, Integer type, String subAgentId) throws Exception {
        return this.upload(serverUrl, type, StrUtil.blankToDefault(subAgentId, agentId), privateKey, filePath);
    }

    @Override
    public UploadFileResponse upload(String serverUrl, Integer type, String agentId, String privateKey, String filePath) throws Exception {
        if (filePath == null) {
            throw new IllegalArgumentException("文件路径不能为空");
        }
        UploadFileResponse response = new UploadFileResponse();
        //下载文件到本地
        File zip = downloadFile(filePath);
        String fileMD5 = DigestUtils.md5Hex(FileUtils.readFileToByteArray(zip));
        UploadVideoRequest request = new UploadVideoRequest();
        request.setFileMD5(fileMD5);
        if (ObjectUtil.isNotNull(type)) {
            request.setType(type);
        }
        Map<String, String> requestMap = Maps.newHashMap();
        getRequestMap(requestMap, privateKey, request, agentId);
        log.info("乐刷文件上传接口请求乐刷入参 >> upload >> url = {}, params = {}，requestMap= {}", serverUrl, JSON.toJSONString(request), requestMap);
        long startTime = System.currentTimeMillis();
        //上传本地路径文件
        String result = FsHttpUtil.postFileMedia(serverUrl, requestMap, zip, 90000);
        log.info("乐刷文件上传接口请求乐刷出参 >> upload >> url = {}, params = {}, result = {}, runTimes = {}", serverUrl, JSON.toJSONString(request), result, System.currentTimeMillis() - startTime);
        if (result == null) {
            return response;
        }
        LeshuaBaseResponse baseResponse = JSON.parseObject(result, LeshuaBaseResponse.class);
        if (baseResponse != null && SUCCESS.equals(baseResponse.getRespCode()) && baseResponse.getData() != null) {
            response.setFileUrl(baseResponse.getData().toString());
        }
        //删除本地文件
        if (zip.exists()) {
            zip.delete();
        }
        return response;
    }


    /**
     * 乐刷调用核心接口
     *
     * @param requestMap
     * @param privateKey
     * @param request
     * @param agentId
     * @throws Exception
     */
    public void getRequestMap(Map<String, String> requestMap, String privateKey, UploadVideoRequest request, String agentId) throws LeshuaException {
        //加签
        String waitSign = SignUtil.SING_PREFIX + privateKey + JSON.toJSONString(request);
        try {
            String sign = Base64.encodeBase64String(BrushMD5.md5(waitSign).getBytes(SignUtil.DEFAULT_CHARSET));
            requestMap.put("agentId", agentId);
            requestMap.put("version", SignUtil.DEFAULT_VERSION);
            requestMap.put("reqSerialNo", ReqSerialNoUtil.getReqSerialNo());
            requestMap.put("sign", sign);
            requestMap.put("data", JSON.toJSONString(request));
        } catch (UnsupportedEncodingException e) {
            log.info("签名异常,e={}", ExceptionUtils.getStackTrace(e));
            throw new LeshuaException("签名异常", e);
        }
    }


    private File downloadFile(String filePath) throws Exception {
        //文件保存的地址
        String savePath = FILE_SAVE_TEMP_DIR + DateUtil.getNowDateStr();
        String path = (new URI(filePath)).getPath();
        String substring = path.substring(path.lastIndexOf(".") - 1);
        //重新生成的文件名 不包括文件类型
        String fileName = RandomStringUtils.randomAlphanumeric(10) + substring;
        //将文件下载到本地指定文件夹
        final String targetFilePath = savePath + File.separator + fileName;
        HttpUtil.downloadFile(filePath, targetFilePath);
        if (StringPool.EMPTY.equals(fileName)) {
            throw new LeshuaException("下载的文件为空");
        }
        return FileUtil.file(targetFilePath);
    }
}